<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>应用状态管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        
        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #7f8c8d;
            font-size: 14px;
        }
        
        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #34495e;
            margin-bottom: 15px;
            font-size: 18px;
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .status-item {
            text-align: center;
            padding: 15px;
            border-radius: 6px;
            background-color: #f8f9fa;
        }
        
        .status-number {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .status-label {
            font-size: 14px;
            color: #666;
        }
        
        .pending .status-number {
            color: #f39c12;
        }
        
        .completed .status-number {
            color: #27ae60;
        }
        
        .failed .status-number {
            color: #e74c3c;
        }
        
        .total .status-number {
            color: #3498db;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s, transform 0.1s;
        }
        
        button:active {
            transform: scale(0.98);
        }
        
        .btn-primary {
            background-color: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
        }
        
        .btn-secondary {
            background-color: #95a5a6;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #7f8c8d;
        }
        
        .btn-danger {
            background-color: #e74c3c;
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #c0392b;
        }
        
        .btn-success {
            background-color: #27ae60;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #229954;
        }
        
        .status-message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 6px;
            background-color: #ecf0f1;
            border-left: 4px solid #3498db;
            font-size: 14px;
        }
        
        .success {
            background-color: #d5f4e6;
            border-left-color: #27ae60;
        }
        
        .error {
            background-color: #fedcd2;
            border-left-color: #e74c3c;
        }
        
        .warning {
            background-color: #fff3cd;
            border-left-color: #f39c12;
        }
        
        .logs-section {
            margin-top: 20px;
        }
        
        .logs-container {
            background-color: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 6px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', Courier, monospace;
            font-size: 13px;
        }
        
        .log-item {
            margin-bottom: 5px;
            padding-left: 20px;
            position: relative;
        }
        
        .log-item::before {
            content: '>';
            position: absolute;
            left: 5px;
            color: #3498db;
        }
        
        .system-info {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 20px;
            font-size: 12px;
            color: #666;
        }
        
        .info-item {
            padding: 5px 10px;
            background-color: #ecf0f1;
            border-radius: 4px;
        }
        
        @media (max-width: 480px) {
            body {
                padding: 15px;
            }
            
            .status-grid {
                grid-template-columns: 1fr;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            button {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>应用状态管理</h1>
        <p class="subtitle">监控和管理离线请求队列与后台同步状态</p>
    </header>
    
    <div class="system-info">
        <span class="info-item" id="network-status">网络状态: 未知</span>
        <span class="info-item" id="service-worker-status">Service Worker: 未激活</span>
        <span class="info-item" id="app-version">应用版本: v2.3</span>
    </div>
    
    <div class="card">
        <h2>请求队列状态</h2>
        <div class="status-grid">
            <div class="status-item total">
                <div class="status-number" id="total-requests">0</div>
                <div class="status-label">总请求数</div>
            </div>
            <div class="status-item pending">
                <div class="status-number" id="pending-requests">0</div>
                <div class="status-label">待处理请求</div>
            </div>
            <div class="status-item completed">
                <div class="status-number" id="completed-requests">0</div>
                <div class="status-label">已完成请求</div>
            </div>
            <div class="status-item failed">
                <div class="status-number" id="failed-requests">0</div>
                <div class="status-label">失败请求</div>
            </div>
        </div>
        
        <div class="button-group">
            <button id="refresh-status" class="btn-primary">刷新状态</button>
            <button id="clear-queue" class="btn-danger">清除队列</button>
            <button id="trigger-sync" class="btn-success">触发同步</button>
            <button id="check-updates" class="btn-secondary">检查更新</button>
        </div>
        
        <div id="status-message" class="status-message">
            请点击上方按钮刷新状态或执行操作
        </div>
    </div>
    
    <div class="card logs-section">
        <h2>操作日志</h2>
        <div id="logs-container" class="logs-container">
            <div class="log-item">状态管理界面已加载</div>
        </div>
    </div>

    <script>
        // 导入模块 - 注意：在浏览器中直接使用ES模块语法需要在script标签中添加type="module"
        // 由于这个HTML可能直接在浏览器中打开，我们使用内联脚本实现基本功能
        
        // 状态元素
        const networkStatusEl = document.getElementById('network-status');
        const swStatusEl = document.getElementById('service-worker-status');
        const totalRequestsEl = document.getElementById('total-requests');
        const pendingRequestsEl = document.getElementById('pending-requests');
        const completedRequestsEl = document.getElementById('completed-requests');
        const failedRequestsEl = document.getElementById('failed-requests');
        const statusMessageEl = document.getElementById('status-message');
        const logsContainerEl = document.getElementById('logs-container');
        
        // 按钮元素
        const refreshStatusBtn = document.getElementById('refresh-status');
        const clearQueueBtn = document.getElementById('clear-queue');
        const triggerSyncBtn = document.getElementById('trigger-sync');
        const checkUpdatesBtn = document.getElementById('check-updates');
        
        // 初始化
        function init() {
            updateNetworkStatus();
            checkServiceWorkerStatus();
            addEventListeners();
        }
        
        // 更新网络状态
        function updateNetworkStatus() {
            const isOnline = navigator.onLine;
            networkStatusEl.textContent = `网络状态: ${isOnline ? '在线' : '离线'}`;
            networkStatusEl.className = `info-item ${isOnline ? 'success' : 'error'}`;
            
            logMessage(`网络状态已${isOnline ? '变为在线' : '变为离线'}`);
        }
        
        // 检查Service Worker状态
        async function checkServiceWorkerStatus() {
            if ('serviceWorker' in navigator) {
                try {
                    const registration = await navigator.serviceWorker.getRegistration();
                    if (registration) {
                        swStatusEl.textContent = 'Service Worker: 已激活';
                        swStatusEl.className = 'info-item success';
                        logMessage('Service Worker 状态: 已激活');
                    } else {
                        swStatusEl.textContent = 'Service Worker: 未注册';
                        swStatusEl.className = 'info-item warning';
                        logMessage('Service Worker 状态: 未注册');
                    }
                } catch (error) {
                    swStatusEl.textContent = 'Service Worker: 检查失败';
                    swStatusEl.className = 'info-item error';
                    logMessage(`检查Service Worker状态失败: ${error.message}`);
                }
            } else {
                swStatusEl.textContent = 'Service Worker: 不支持';
                swStatusEl.className = 'info-item error';
                logMessage('浏览器不支持Service Worker');
            }
        }
        
        // 更新请求队列状态
        async function updateQueueStatus() {
            try {
                // 在实际项目中，这里应该调用networkService.getQueueStatus()
                // 由于我们使用内联脚本，这里提供一个模拟实现
                
                // 模拟API调用延迟
                await new Promise(resolve => setTimeout(resolve, 300));
                
                // 模拟数据 - 在实际项目中应该从IndexedDB获取
                const mockStatus = {
                    total: Math.floor(Math.random() * 10),
                    pending: Math.floor(Math.random() * 5),
                    completed: Math.floor(Math.random() * 5),
                    failed: Math.floor(Math.random() * 3)
                };
                
                totalRequestsEl.textContent = mockStatus.total;
                pendingRequestsEl.textContent = mockStatus.pending;
                completedRequestsEl.textContent = mockStatus.completed;
                failedRequestsEl.textContent = mockStatus.failed;
                
                showStatusMessage('队列状态已更新', 'success');
                logMessage('队列状态已更新');
                
                return mockStatus;
            } catch (error) {
                showStatusMessage(`更新队列状态失败: ${error.message}`, 'error');
                logMessage(`更新队列状态失败: ${error.message}`);
                throw error;
            }
        }
        
        // 清除请求队列
        async function clearRequestQueue() {
            try {
                // 在实际项目中，这里应该调用networkService.clearRequestQueue()
                // 模拟API调用延迟
                await new Promise(resolve => setTimeout(resolve, 500));
                
                // 重置UI状态
                totalRequestsEl.textContent = '0';
                pendingRequestsEl.textContent = '0';
                completedRequestsEl.textContent = '0';
                failedRequestsEl.textContent = '0';
                
                showStatusMessage('请求队列已清空', 'success');
                logMessage('请求队列已清空');
            } catch (error) {
                showStatusMessage(`清除队列失败: ${error.message}`, 'error');
                logMessage(`清除队列失败: ${error.message}`);
            }
        }
        
        // 触发后台同步
        async function triggerBackgroundSync() {
            try {
                if ('serviceWorker' in navigator && 'SyncManager' in window) {
                    // 模拟API调用延迟
                    await new Promise(resolve => setTimeout(resolve, 800));
                    
                    showStatusMessage('后台同步请求已发送，网络恢复时将自动执行', 'success');
                    logMessage('后台同步请求已发送');
                } else {
                    showStatusMessage('浏览器不支持后台同步功能', 'warning');
                    logMessage('浏览器不支持后台同步功能');
                }
            } catch (error) {
                showStatusMessage(`触发同步失败: ${error.message}`, 'error');
                logMessage(`触发同步失败: ${error.message}`);
            }
        }
        
        // 检查更新
        async function checkForUpdates() {
            try {
                if ('serviceWorker' in navigator) {
                    // 模拟API调用延迟
                    await new Promise(resolve => setTimeout(resolve, 1000));
                    
                    showStatusMessage('正在检查更新...', 'info');
                    logMessage('正在检查更新...');
                    
                    // 模拟检查结果
                    const hasUpdate = Math.random() > 0.7;
                    
                    if (hasUpdate) {
                        showStatusMessage('发现新版本，正在下载更新...', 'success');
                        logMessage('发现新版本');
                    } else {
                        showStatusMessage('当前已是最新版本', 'info');
                        logMessage('当前已是最新版本');
                    }
                } else {
                    showStatusMessage('浏览器不支持Service Worker更新检查', 'warning');
                    logMessage('浏览器不支持Service Worker更新检查');
                }
            } catch (error) {
                showStatusMessage(`检查更新失败: ${error.message}`, 'error');
                logMessage(`检查更新失败: ${error.message}`);
            }
        }
        
        // 显示状态消息
        function showStatusMessage(message, type = 'info') {
            statusMessageEl.textContent = message;
            statusMessageEl.className = 'status-message';
            
            switch (type) {
                case 'success':
                    statusMessageEl.classList.add('success');
                    break;
                case 'error':
                    statusMessageEl.classList.add('error');
                    break;
                case 'warning':
                    statusMessageEl.classList.add('warning');
                    break;
                default:
                    // 默认为info状态，不添加额外类
            }
        }
        
        // 记录日志
        function logMessage(message) {
            const timestamp = new Date().toLocaleTimeString();
            const logItem = document.createElement('div');
            logItem.className = 'log-item';
            logItem.textContent = `[${timestamp}] ${message}`;
            
            logsContainerEl.appendChild(logItem);
            
            // 自动滚动到底部
            logsContainerEl.scrollTop = logsContainerEl.scrollHeight;
        }
        
        // 添加事件监听器
        function addEventListeners() {
            // 网络状态变化监听
            window.addEventListener('online', updateNetworkStatus);
            window.addEventListener('offline', updateNetworkStatus);
            
            // 按钮点击事件
            refreshStatusBtn.addEventListener('click', updateQueueStatus);
            clearQueueBtn.addEventListener('click', clearRequestQueue);
            triggerSyncBtn.addEventListener('click', triggerBackgroundSync);
            checkUpdatesBtn.addEventListener('click', checkForUpdates);
            
            // Service Worker消息监听
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.addEventListener('message', event => {
                    const data = event.data;
                    if (data.type === 'SYNC_RESULTS') {
                        logMessage(`收到同步结果: 成功 ${data.successful || 0} 个请求，失败 ${data.failed || 0} 个请求`);
                        showStatusMessage(`同步完成: 成功 ${data.successful || 0} 个请求，失败 ${data.failed || 0} 个请求`, 
                                          data.successful > 0 ? 'success' : 'error');
                        // 同步完成后更新状态
                        updateQueueStatus();
                    }
                });
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>